import { SocketServer } from "@/App";
import HJRequest from "@/utils/request";
import { message } from "antd";
import NProgress from "nprogress";
export * from "./format";
export interface IPageConfig {
  label: string;
  key: string;
  type:
  | "string"
  | "select"
  | "custom"
  | "date"
  | "datePick"
  | "number"
  | "Cascader";
  placeholder: string;
}
export const request = new HJRequest({
  baseURL: "http://localhost:12345",
  timeout: 100000,
  interceptors: {
    requestInterceptor: (config) => {
      const token = localStorage.getItem("token");
      NProgress.start();
      const n = document.querySelector("#root") as HTMLElement;
      n.style.position = "absolute";
      n.style.zIndex = "-10";
      if (token) {
        config.headers!.Authorization = token;
      } else {
        location.href = "#/login"
      }
      return config;
    },
    responseInterceptor(res) {
      setTimeout(() => {
        NProgress.done();
        const n = document.querySelector("#root") as HTMLElement;
        n.style.position = "absolute";
        n.style.zIndex = "1";
      }, 500);
      console.log("=> ----- ", res);
      
      if (res.data.msg === "无效token" || res.data.msg === "请重新登录") {
        message.error("登录过期了!! 如果有数据在编写请保存 重新登录再操作!");
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        SocketServer?.close()
        // setTimeout(() => location.replace("/"), 500);
      }
      return res;
    },
    requestInterceptorError(err) {
      setTimeout(() => {
        NProgress.done();
        const n = document.querySelector("#root") as HTMLElement;
        n.style.position = "absolute";
        n.style.zIndex = "1";
      }, 500);
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      SocketServer?.close()
      // setTimeout(() => location.replace("/"), 600);
      return err;
    },
    responseInterceptorError(error) {
      setTimeout(() => {
        NProgress.done();
        const n = document.querySelector("#root") as HTMLElement;
        n.style.position = "absolute";
        n.style.zIndex = "1";
      }, 500);
      message.error({ content: "请求出现错误!", duration: 3 });
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      SocketServer?.close()
      // setTimeout(() => location.replace("/"), 500);
      return error;
    },
  },
});
export function ByStatusReturnAuditsProgress(item = null) {
  console.log("item", item);

  if (!item.Approved) {
    return <span>审核中</span>;
  } else if (item.Rejection != "") {
    return <span className="text-red-500">已驳回</span>;
  } else if (item.Approved) {
    return <span className="text-green-500">已通过</span>;
  } else {
    return <span>申请中</span>;
  }
}
export function handleAttributeData(data: any) {
  try {
    let { parent, children } = data;
    parent?.map((item: any) => {
      item.children = [];
      return {
        ...item,
        children: children?.map((itemx: any) => {
          itemx.children = [];
          if (item.id === itemx.is_parent) {
            item.children.push(itemx);
          }
          children.map((itemz: any) => {
            if (itemx.id === itemz.is_parent) {
              itemx.children.push(itemz);
            }
          });
        }),
      };
    });
    return parent;
  } catch (error) {
    console.log("first err: ", error);
  }
}

export function filterWarehouseData(type: string, data: any[]) {
  const arr: any[] = [];
  if (type == "item_type") {
    data.forEach((Item: any) => {
      if (arr.indexOf(Item.item_type) == -1) {
        arr.push(Item.item_type);
      }
    });
    return arr.map((item) => ({
      value: item,
      label: item,
    }));
  }
  data.forEach((Item: any) => {
    if (arr.indexOf(Item.item_name) == -1) {
      arr.push(Item.item_name);
    }
  });
  return arr.map((item) => ({
    value: item,
    label: item,
  }));
}
export const ExcludeAttribute = [
  "ID",
  "CreatedAt",
  "UpdatedAt",
  "is_edit",
  "DeletedAt",
  "key",
];
export const WareHouseStatus = [
  {
    msg: "销售",
    color: "#f50",
  },
  {
    msg: "转销",
    color: "#EE1289",
  },
  {
    msg: "借测",
    color: "#FFA500",
  },
  {
    msg: "内部测试",
    color: "#8A2BE2",
  },
  {
    msg: "采购直发",
    color: "#f00",
  },
  {
    msg: "借测转销",
    color: "#f89",
  },
  {
    msg: "补单",
    color: "#89f",
  },
];
export const WareHouseProgress = [
  {
    msg: "进行中",
    color: "#f00",
  },
  {
    msg: "已完成",
    color: "#0f0",
  },
  {
    msg: "已还库",
    color: "#00f",
  },
  {
    msg: "已转销",
    color: "#f0f",
  },
  {
    msg: "退还库",
    color: "#f84",
  },
];
// 返回筛选的数据
export function returnOrderOptions(key: string, users?: any[]) {
  if (key == "status") {
    return WareHouseStatus.map((itemy, index) => ({
      value: index,
      label: itemy.msg,
    }));
  }
  if (users && key == "operate_member") {
    return users.map((item) => ({
      label: item.user_name,
      value: item.user_name,
    }));
  }
  return WareHouseProgress.map((item, index) => ({
    value: index,
    label: item.msg,
  }));
}

export function returnQueryUrlByData(data: any) {
  let query = "";
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];
      if (query == "" && element) {
        query = `?${key}=${element}`;
      } else if (query != "" && element) {
        query += `&${key}=${element}`;
      }
    }
  }
  return query;
}

// 防抖函数
export function debounce(func, wait = 500, immediate = false) {
  let timeout;
  return function (...args) {
    const context = this;
    const later = function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}
